package com.sali.file;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ChunkedFileReceiver {
    public static void main(String[] args) throws IOException {
        String serverUrl = "http://localhost:8080/file"; // 替换为实际的服务端地址

        URL url = new URL(serverUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        // 打开连接
        connection.connect();

        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            InputStream inputStream = connection.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream("/Users/zhanghang/Desktop/test4-left-8000-2.wav"); // 本地文件名

            byte[] buffer = new byte[1024];
            int bytesRead;
            boolean isChunkedData = false;
            long totalFileSize = 0;

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                if (isChunkedData) {
                    // 如果正在接收chunked数据，写入文件
                    fileOutputStream.write(buffer, 0, bytesRead);
                    totalFileSize += bytesRead;
                } else {
                    // 如果没有开始接收chunked数据，检查是否是chunked数据开始标志
                    String line = new String(buffer, 0, bytesRead);
                    if (line.trim().isEmpty()) {
                        isChunkedData = true;
                    }
                }
            }

            fileOutputStream.close();
            inputStream.close();
            connection.disconnect();
            System.out.println("File received successfully. Total size: " + totalFileSize + " bytes");
        } else {
            System.err.println("Error: " + responseCode);
        }
    }
}
